package sin.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;

import sin.entity.Student;
import sin.entity.Teacher;
import sin.service.StudentService;
import sin.service.TeacherService;
import sin.utils.SakUtils;
import sin.utils.ServletUtils;

@Controller
@RequestMapping("/teacherController")
public class TeacherController {
	
	@Autowired
	private StudentService studentService;
	@Autowired
	private TeacherService teacherService;

	@RequestMapping(value = "/chooseStudent")
	public void chooseStudent(String ids, HttpServletRequest request, HttpServletResponse response) {
		if(StringUtils.isBlank(ids)) {
			ServletUtils.output(response, new Gson().toJson(SakUtils.toMap("error","id不能为空！")));
			return;
		}
		
		Teacher teacher = (Teacher) request.getSession().getAttribute("currentTeacher");
		
		if(SakUtils.isBlank(teacher)) {
			ServletUtils.output(response, new Gson().toJson(SakUtils.toMap("error","教师尚未登陆！")));
			return;
		}
		
		for(String id : ids.split(",")) {
			Student student = studentService.getById(id);
			if(student != null) {
				student.setTeacherIds(student.getTeacherIds() + "," + teacher.getId());
				studentService.saveStudent(student);
			}
		}
		
		teacher.setStudentIds(teacher.getStudentIds() + "," + ids);
		teacherService.saveTeacher(teacher);
	}
	
}
